package com.lsh.oms.provider.service.order.ka;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;
import com.alibaba.fastjson.JSON;
import com.lsh.base.common.json.JsonUtils;
import com.lsh.base.common.model.CommonResult;
import com.lsh.oms.api.model.order.OrderReceiptKADTO;
import com.lsh.oms.api.service.order.ka.IKaOrderReceiptRestService;
import com.lsh.oms.core.constant.ReturnCode;
import com.lsh.oms.core.enums.OrderStatus;
import com.lsh.oms.core.exception.BusinessException;
import com.lsh.oms.core.exception.ExceptionStatus;
import com.lsh.oms.core.model.order.OrderHead;
import com.lsh.oms.core.service.order.OrderQueryService;
import com.lsh.oms.core.service.order.frozen.OrderReceiptFrogenService;
import com.lsh.oms.core.service.tool.ToolService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.concurrent.TimeUnit;

/**
 * Project Name: lsh-oms
 *
 * @author miaozhuang
 * @date 17/3/27
 * 北京链商电子商务有限公司
 * Package
 * desc:订单签收RestService
 */
@Service(protocol = "rest", timeout = 30000)
@Path("order/receipt/ka")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({ContentType.APPLICATION_JSON_UTF_8})
public class KaOrderReceiptRestServiceImpl implements IKaOrderReceiptRestService {

    private static Logger logger = LoggerFactory.getLogger(KaOrderReceiptRestServiceImpl.class);

    @Autowired
    private OrderQueryService orderQueryService;

    @Autowired
    private OrderReceiptFrogenService orderReceiptFrogenService;

    @POST
    @Path("create")
    @Override
    public CommonResult<Object> create(OrderReceiptKADTO receiptDTO) {
        String logSign = "logSign : " + ToolService.getLogSign();

        CommonResult<Object> commonResult = new CommonResult<>();

        try {
            OrderHead orderHead = this.checkPara(receiptDTO, logSign);

            commonResult = this.orderReceiptFrogenService.createReceiptFromShip(orderHead, logSign);

            logger.info("【KA】commonResult-receipt-" + receiptDTO.getOrderCode() + JSON.toJSONString(commonResult));
        } catch (BusinessException e) {
            commonResult.setCode(e.getCode());
            commonResult.setMessage(e.getMessage());
            logger.error("业务异常code : " + e.getCode() + ",异常信息: " + e.getMessage(), e);
        } catch (Exception e) {
            commonResult.setCode(ExceptionStatus.E3001001.getCode());
            commonResult.setMessage(ExceptionStatus.E3001001.getMessage());
            logger.error("业务异常code : " + ExceptionStatus.E3001001.getCode(), e);
        }

        return commonResult;
    }


    /**
     * @param receiptDTO 参数
     * @return OrderHead
     */
    private OrderHead checkPara(OrderReceiptKADTO receiptDTO, String logSign) {

        if (receiptDTO == null) {
            throw new BusinessException(ReturnCode.REQUEST_PARAMS_IS_NULL, "请求参数不合法，请检验。");
        }

        logger.info(logSign + ":【KA】签收入参 －－ {}", JsonUtils.obj2Json(receiptDTO));

        if (receiptDTO.getOrderCode() == null) {
            throw new BusinessException(ReturnCode.REQUEST_PARAMS_IS_NULL, "请求参数不合法，请检验。");
        }

        OrderHead orderHead = orderQueryService.findByCode(receiptDTO.getOrderCode(), true, false);
        if (orderHead == null) {
            throw new BusinessException(ReturnCode.FIND_ORDER_IS_NULL, "用户订单号未查询到订单");
        }

        //签收发生在发货以后
        if (orderHead.getOrderStatus().compareTo(OrderStatus.ORDER_DELIVERY.getIndex()) < 0) {
            throw new BusinessException(ReturnCode.ORDER_STATUS_ERROR, "订单状态是" + OrderStatus.getName(orderHead.getOrderStatus()) + "，请检验。");
        }

        int ts = (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
        orderHead.setUpdateTime(ts);

        return orderHead;
    }


    @POST
    @Path("/create/confirm")
    @Override
    public CommonResult<Object> confirm(OrderReceiptKADTO receiptDTO) {
        String logSign = "logSign : " + ToolService.getLogSign();
        logger.info(logSign + ": confirm KA（确认签收）入参 －－ " + (receiptDTO == null ? "" : JsonUtils.obj2Json(receiptDTO)));

        CommonResult<Object> commonResult = new CommonResult<>();

        try {
            OrderHead orderHead = this.checkPara(receiptDTO, logSign);

            commonResult = this.orderReceiptFrogenService.isCreateReceiptBill(orderHead);

            logger.info("confirm_commonResult-receipt-" + receiptDTO.getOrderCode() + JSON.toJSONString(commonResult));
        } catch (BusinessException e) {
            commonResult.setCode(e.getCode());
            commonResult.setMessage(e.getMessage());
            logger.error("业务异常code : " + e.getCode() + ",异常信息: " + e.getMessage(), e);
        } catch (Exception e) {
            commonResult.setCode(ExceptionStatus.E3001001.getCode());
            commonResult.setMessage(ExceptionStatus.E3001001.getMessage());
            logger.error("业务异常code : " + ExceptionStatus.E3001001.getCode(), e);
        }

        return commonResult;
    }
}
